<template>
  <view class="familyCircleDetails flex flex-column align-center">
    <s-header-title ref="headerTitle" :isShowHome="options.is_share == 1 && options.is_show != 1"
                    :isDisplayBack="options.is_share != 1 || options.is_show == 1"
                    title="家庭圈" is-fixed
                    background="#FFFFFFF"
                    @getPageHeight="getPageHeight">
      <!--      <template>-->
      <!--        <view class="uploadPhoto_headerTitle">-->
      <!--          <text v-if="options.is_share != 1" class="uploadPhoto_headerTitle_text">-->
      <!--            {{-->
      <!--              options.is_flag != 1 ? options.name : selectedFamilyDetail.familyName ? selectedFamilyDetail.familyName : '暂无家庭名称'-->
      <!--            }}-->
      <!--          </text>-->
      <!--          <text v-else class="uploadPhoto_headerTitle_text">-->
      <!--            {{-->
      <!--              options.is_flag != 1 ? options.name : options.shareName-->
      <!--            }}-->
      <!--          </text>-->
      <!--        </view>-->
      <!--      </template>-->
    </s-header-title>
    <view :style="{height:`${headerHeight}px`}"></view>
    <family-circle class="familyCircle"
                   id="familyCircle"
                   ref="familyCircle"
                   v-for="(item,index) in familyCircleDetail"
                   :detailFlag="true"
                   :key="index"
                   :info="item"
                   :index="index"
                   :is_share="options.is_share == 1"
                   :is_nav="options.is_detail != 1"
                   :options="options"
                   :is-show-del="options.is_detail == 1"
                   :commentsList="list"
                   @likeInterface="likeInterface"
                   @secondLevelReplies="secondLevelReplies"
                   @topLevelReplies="topLevelReplies"
                   @familyCircleReview="familyCircleReview"
                   @openLogin="openLogin"
                   @openCreateUser="openCreateUser"
                   @delCommentById="delCommentById"
                   @shareAppMessage="shareAppMessage"
    ></family-circle>
    <!--  朋友圈评论  -->
    <view class="photoDetails_comments flex align-end justify-between z_10"
          :style="{
            bottom:commentsHeight+'px'
          }"
          v-if="options.is_detail == 1 && options.is_share != 1"
    >
      <view
        style="position: absolute;width: 750rpx;top: -30rpx;left: 50%;transform: translateX(-50%);overflow: hidden;background: #FFFFFF;padding:10rpx 0"
        class="fs_24 flex align-center fw_500 color_4B4B4B"
        v-if="!!commentReply"
      >
        <view style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width: 710rpx;"
              class="ml_24 mr_12"
        >
          {{ commentReply }}
        </view>
        <image class="wh_24 hW_24 mr_24" :src="`${IMG_URL}/index/update_close.png`" @click.stop="closeReply()"></image>
      </view>
      <view class="photoDetails_comments_left ml_24">
        <textarea class="photoDetails_comments_left_input" v-model="commentsValue" :focus="commentsFocus"
                  placeholder="评论" :adjust-position="false" maxlength="200" auto-height @blur="commentBlur"
                  @focus="inputFocus"></textarea>
      </view>
      <view class="photoDetails_comments_right mr_24 flex align-center justify-center" :style="{
       background: commentsValue == '' ? '#9F9F9F' : '#FF6D00'
      }" @click.stop="debounce(photoComments,500,true)">
        <text class="photoDetails_comments_right_text">完成</text>
      </view>
    </view>
    <view style="height: 200rpx"></view>
  </view>
</template>

<script>

  import FamilyCircle from '@/pages/familyPage/components/familyCircle.vue';
  import HeaderTitle from '@/pages/familyPage/components/headerTitle.vue';
  import sheep from '@/sheep';
  import debounce from '@/sheep/helper/debounce';

  export default {
    components: { FamilyCircle, HeaderTitle },
    data() {
      return {
        // 头部高度
        headerHeight: 0,
        familyCircleDetail: [],
        // 获取家庭圈搜索参数
        searchParams: {
          page: 1,
          pagesize: 10,
          family_id: '',
          type: 1,
          total: 0,
        },
        // 浮窗按钮的配置
        bottomFlag: false,
        systemInfo: {},
        commentsHeight: 0,
        commentsValue: '',
        commentsFocus: false,
        inputValue: {},
        getImageCommentParams: {
          moment_id: '',
          page: 1,
          pagesize: 10,
          total: 0,
        },
        list: [],
        commentReply: '',
      };
    },
    props: {
      options: {
        type: Object,
        default: {},
      },
    },
    computed: {
      token() {
        return sheep.$store('user').isLogin;
      },
      IMG_URL() {
        return sheep.$store('AI').sq_image_path;
      },
    },
    onLoad(options) {
      this.options = options;
      this.getOptions(options);
      // 监听键盘的高度
      uni.onKeyboardHeightChange(this.onKeyboardHeightChange);
      if (this.options.is_share == 1 && this.options.is_flag == 1) {
        this.getFamilyInfo();
      }
    },
    onReady() {
      uni.$on('delectClecir', () => {
        this.familyCircleDetail = [];
        this.getFamilyCircle();
      });
      // this.getFamilyCircle()
      this.$nextTick(() => {
        this.systemInfo = uni.getSystemInfoSync();
        this.getBottomButton();
      });
    },
    mounted() {
      if (this.options.is_showComment == 1) {
        setTimeout(() => {
          this.commentsFocus = true;
        }, 500);
      }
    },
    onShow() {
      this.searchParams.page = 1;
      this.familyCircleDetail = [];
      this.getFamilyCircle();
      if (this.options.is_share == 1) {
        this.getFamilyInfo();
      }
    },
    onReachBottom() {
      if (this.familyCircleDetail.length < this.searchParams.total) {
        this.searchParams.page++;
        this.getFamilyCircle();
      }
    },
    onUnload() {
      // 关闭键盘监听事件
      uni.offKeyboardHeightChange(this.onKeyboardHeightChange);
    },
    methods: {
      debounce,
      async getFamilyInfo() {
        console.log('this.options.family_id=>', this.options.family_id);
        if (!this.options.family_id || this.options.family_id == 'undefined') {
          return;
        }
        let { data } = await shiQinGetFamilyDetail({
          family_id: this.options.family_id,
        });
        this.$nextTick(() => {
          this.$set(this.options, 'shareName', data.detail.familyName);
        });
      },
      openCreateUser(data) {
        this.$refs.secondPopup.openPopup({
          background: `${this.IMG_URL}personalInformation.png`,
          memberInfo: data,
        });
      },
      getBottomButton() {
        const query = uni.createSelectorQuery().in(this);
        query.selectAll('.familyCircle').boundingClientRect(data => {
          let num = 0;
          data.forEach(item => {
            num = item.top + item.height + num;
          });
          const rpx = this.systemInfo.windowWidth / 750;
          console.log(num);
          this.bottomFlag = (this.headerHeight + num) > this.systemInfo.windowHeight - (200 * rpx);
        }).exec();
      },
      getPageHeight(number) {
        this.headerHeight = number;
      },
      // 获取家庭全接口
      async getFamilyCircle() {
        if (this.options.is_detail != 1) {
          this.searchParams.family_id = this.options.is_share != 1 ? this.family_id : this.options.family_id;
          this.searchParams.type = this.options.is_flag != 1 ? 2 : 1;
          if (this.options.is_flag != 1) {
            this.searchParams.member_id = this.options.member_id;
          }
          let { data } = await getMomentsList(this.searchParams);
          this.searchParams.total = data.list.total;
          data.list.data.forEach(item => {
            this.familyCircleDetail.push(item);
          });
        } else {
          let { data } = await sheep.$api.family.getFamilyCircleDetail({ id: this.options.id });
          this.familyCircleDetail.push(data);
          // if (this.options.is_share == 1) {
          //   let info = await shiQinGetFamilyDetail({family_id: this.familyCircleDetail[0].family_id})
          //   this.options.shareName = info.data.detail.familyName
          // }
        }

        this.$nextTick(() => {
          this.getBottomButton();
        });
      },
      // 家庭圈点赞
      likeInterface(index) {
        this.$set(this.familyCircleDetail[index], 'like_count', this.familyCircleDetail[index].like_count + 1);
        this.$set(this.familyCircleDetail[index], 'is_like', 1);
        uni.$emit('friendsCircleLike', this.familyCircleDetail[index]);
      },
      commentBlur() {
        this.commentsFocus = false;
      },
      inputFocus() {
      },
      async photoComments() {
        if (!this.token) {
          this.$refs.loginPopup.openPopup();
          return;
        }
        const data = await sheep.$api.family.checkAuth({
          family_id: this.options.family_id,
          action: 'add',
        });
        if (data.code != 1) {
          sheep.$helper.toast(data.msg);
          return;
        }
        if (this.commentsValue == '') {
          sheep.$helper.toast('请输入评论内容');
          return;
        }
        let { code, msg } = await sheep.$api.family.addComment({
          comment_id: this.familyCircleDetail[0].id,
          content: this.commentsValue,
          type: 1,
          pid: this.inputValue.pid,
          top_id: this.inputValue.top_id,
        });
        if (code == 1) {
          this.commentsValue = '';
          sheep.$helper.toast('评论成功');
          this.familyCircleDetail[0].comment_count++;
          this.commentsFocus = false;
          // this.familyCircleDetail[0].children.push(data);
          this.commentReply = '';
          await this.getCommentList();
        } else {
          sheep.$helper.toast(msg);
        }
      },
      async delCommentById(info) {
        await this.getCommentList();
      },
      secondLevelReplies(info, info2) {
        this.inputValue = {
          moments_id: info.tid,
          content: this.commentsValue,
          comment_id: info.id,
          record_id: info2.id,
        };
        this.isChildren = true;
        this.commentsFocus = true;
      },
      async topLevelReplies(info) {
        console.log(info);
        this.commentReply = `回复${info.user_nickname}: ${info.content}`;
        this.inputValue = {
          pid: info.id,
        };
        if(!!info.top_id){
          this.inputValue = {
            pid: info.id,
            top_id:info.top_id
          };
        }
        this.isChildren = true;
        this.commentsFocus = true;
      },
      closeReply() {
        this.commentReply = '';
      },
      familyCircleReview() {
        this.commentsFocus = true;
      },
      onKeyboardHeightChange(res) {
        const { height, duration } = res;
        // 键盘弹起
        if (height > 0) {
          this.commentsHeight = height;
        }
        // 键盘收回
        else {
          this.commentsHeight = height;
        }
      },
      async shareAppMessage(obj) {
        // #ifdef APP-PLUS
        uni.showLoading({
          title: '分享中，请稍后...',
        });
        let title = obj.title || '重拾亲情，孝道传承...';
        let path = obj.path || '';
        let imageInfo = await this.$appShare.getImageInfo(obj.imageUrl);
        console.log('当前图片信息=>', imageInfo);
        if (imageInfo.info.size > 20000) {
          this.$nextTick(() => {
            this.$set(this, 'canvasWidth', 240);
            this.$set(this, 'canvasHeight', Math.round(imageInfo.path.height * (240 / imageInfo.path.width)));
            let ctx = uni.createCanvasContext('canvasShare');
            ctx.setFillStyle('#FFFFFF');
            ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
            console.log('绘制的图片=>', imageInfo.path.path, this.canvasWidth, this.canvasHeight);
            ctx.drawImage(imageInfo.path.path, 0, 0, this.canvasWidth, this.canvasHeight);
            ctx.draw(true, () => {
              setTimeout(() => {
                uni.canvasToTempFilePath({
                  canvasId: 'canvasShare',
                  width: this.canvasWidth,
                  height: this.canvasHeight,
                  destWidth: this.canvasWidth * 2,
                  destHeight: this.canvasHeight * 2,
                  quality: 1,
                  success: (res) => {
                    uni.uploadFile({
                      url: `${HTTP_REQUEST_URL}/api/upload/image`,
                      filePath: res.tempFilePath,
                      fileType: 'image',
                      name: 'pics',
                      formData: {
                        'filename': 'pics',
                      },
                      header: {
                        // #ifdef MP
                        'Content-Type': 'multipart/form-data',
                        // #endif
                        [TOKENNAME]: 'Bearer ' + this.$store.state.app.token,
                      },
                      success: async (res) => {
                        console.log('生成的图片信息=>', JSON.parse(res.data).data.url);
                        this.$appShare.appShare(
                          false,
                          'WXSceneSession',
                          5,
                          JSON.parse(res.data).data.url,
                          title,
                          path,
                        );
                      },
                    });
                  },
                });
              }, 1500);
            });
          });
        } else {
          this.$appShare.appShare(
            false,
            'WXSceneSession',
            5,
            obj.imageUrl,
            title,
            path,
          );
        }
        // #endif
        // #ifdef MP-WEIXIN
        console.log(obj);
        this.wxShare.title = obj.title || '重拾亲情，孝道传承...';
        this.wxShare.path = obj.path || '';
        this.wxShare.imageUrl = obj.imageUrl || '';
        setTimeout(() => {
          this.wxShare.title = '重拾亲情，孝道传承...';
          this.wxShare.path = '/pages/family/index';
        }, 1000);
        // #endif
      },
      openLogin() {
        this.$refs.loginPopup.openPopup();
      },
      getOptions(options) {
        let that = this;
        // #ifdef MP
        if (options.scene) {
          let value = that.$util.getUrlParams(decodeURIComponent(options.scene));
          //记录推广人uid
          if (value.spid) app.globalData.spid = value.spid;
        }
        // #endif
        if (options.spid) app.globalData.spid = options.spid;
      },
      // 获取评论列表
      async getCommentList() {
        if (this.familyCircleDetail.length == 1) {
          const { data } = await sheep.$api.family.getCommentList({
            comment_id: this.familyCircleDetail[0].id,
            type: 1,
            page: 0,
          });
          this.list = data;
        }
      },
      setHeightCommit() {
        uni.onKeyboardHeightChange(this.onKeyboardHeightChange);
      },
    },
  };
</script>

<style lang="scss">
  .familyCircleDetails {
    width: 750rpx;
    min-height: 100vh;
    background: #F5F5F5;
    overflow: hidden;
    margin: 0 auto;

    .familyCircleDetails_headerTitle {
      position: absolute;
      bottom: -26rpx;
      left: 50%;
      transform: translateX(-50%);

      .familyCircleDetails_headerTitle_text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 20rpx;
        color: #A0A0A0;
      }
    }

    .familyCircleDetails_publish {
      width: 362rpx;
      height: 80rpx;
      background: #FF4206;
      border-radius: 41rpx 41rpx 41rpx 41rpx;
      position: fixed;
      bottom: 50rpx;
      left: 50%;
      transform: translateX(-50%);
      z-index: 10;

      .familyCircleDetails_publish_text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 30rpx;
        color: #FFFFFF;
      }
    }

  }


  .uploadPhoto_headerTitle {
    position: absolute;
    bottom: -26rpx;
    left: 50%;
    transform: translateX(-50%);

    .uploadPhoto_headerTitle_text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 20rpx;
      color: #A0A0A0;
    }
  }

  .photoDetails_comments {
    width: 750rpx;
    background: #FFFFFF;
    padding: 22rpx 0 42rpx 0;
    position: fixed;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);

    .photoDetails_comments_left {
      width: 540rpx;
      //height: 80rpx;
      background: #FFFFFF;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      border: 1rpx solid #707070;
      padding: 20rpx 20rpx 20rpx 20rpx;

      .photoDetails_comments_left_input {
        width: 537rpx;
        min-height: 40rpx;
        max-height: 150rpx;
      }
    }

    .photoDetails_comments_right {
      width: 115rpx;
      height: 80rpx;
      background: #9F9F9F;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      //border: 1rpx solid #707070;

      .photoDetails_comments_right_text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 23rpx;
        color: #FFFFFF;
      }
    }
  }

  .listOfReviews {
    width: 656rpx;

    .likeList {
      .likeList_image {
        width: 21rpx;
        height: 21rpx;
      }

      .likeList_text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 24rpx;
        color: #656565;
      }
    }
  }

  .photoDetails_comments {
    width: 750rpx;
    background: #FFFFFF;
    padding: 22rpx 0 42rpx 0;
    position: fixed;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);

    .photoDetails_comments_left {
      width: 540rpx;
      //height: 80rpx;
      background: #FFFFFF;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      border: 1rpx solid #707070;
      padding: 20rpx 20rpx 20rpx 20rpx;

      .photoDetails_comments_left_input {
        width: 537rpx;
        min-height: 40rpx;
        max-height: 150rpx;
      }
    }

    .photoDetails_comments_right {
      width: 115rpx;
      height: 80rpx;
      background: #9F9F9F;
      border-radius: 20rpx 20rpx 20rpx 20rpx;
      //border: 1rpx solid #707070;

      .photoDetails_comments_right_text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 23rpx;
        color: #FFFFFF;
      }
    }
  }

  .listOfReviews {
    width: 656rpx;

    .likeList {
      .likeList_image {
        width: 21rpx;
        height: 21rpx;
      }

      .likeList_text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 24rpx;
        color: #656565;
      }
    }
  }

  .listOfReviews {

  }
</style>
